package com.zdya.combatdocuments.p2pNetwork;

import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.zdya.combatdocuments.entity.Node;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.java_websocket.WebSocket;
import org.java_websocket.client.WebSocketClient;
import org.java_websocket.handshake.ServerHandshake;
import org.springframework.stereotype.Component;

import java.net.URI;
import java.net.URISyntaxException;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;

@Component
@Slf4j
@Data
public class P2pClientBrowser {
    private WebSocket webSocket = null;

    private List<WebSocket> webSocketList = new CopyOnWriteArrayList<WebSocket>();

    private String wsUrl = "ws://127.0.0.1:8001";

    public void connectPeer(){
        try{
            //创建websocket的客户端
            final WebSocketClient socketClient=new WebSocketClient(new URI(wsUrl)) {

                @Override
                public void onOpen(ServerHandshake serverHandshake) {
                    webSocket = this;
                    webSocketList.add(this);
                    log.info("ClientBrowser连接上本机服务端");
                }

                @Override
                public void onMessage(String msg) {
                    log.info("receiveMsg:"+msg);
                }

                @Override
                public void onClose(int i, String msg, boolean b) {
                    log.info("connection closed");
                    webSocketList.remove(this);
                }

                @Override
                public void onError(Exception e) {
                    webSocketList.remove(this);
                    log.info("connection failed");
                }
            };
            //客户端开始连接服务器
            socketClient.connect();
        }catch (URISyntaxException e){
            log.info("p2p connect is error:" + e.getMessage());
        }
    }

    /**
     * 发送消息
     * @param ws
     * @param message
     */
    public void write(WebSocket ws, String message) {
        log.info("发送给IP地址为：" +ws.getRemoteSocketAddress().getAddress().toString() + "的p2p消息:" + message);
        ws.send(message);
    }

    /**
     * 全网广播消息
     * @param message
     */
    public synchronized void broadcast(String message) {
        List<WebSocket> webSocketList = this.webSocketList;
        if (CollectionUtils.isEmpty(webSocketList)) {
            return;
        }
        log.info("======全网广播消息开始：");
        for (WebSocket webSocket : webSocketList) {
            this.write(webSocket, message);
        }
        log.info("======全网广播消息结束");
    }


}
